/**
 * 功能商店
 */
import React from "react";
import { Card, Row, Col, Button, message } from "antd";
import api from "../../api";
import style from "./modulelist.module.scss";
import Iconfont from "../../util/iconfont";
import LibraryJs from "../../library/js"; // 公共工具类

class ModuleList extends React.Component {
  constructor() {
    super();
    this.state = {
      modulelist: [],
      checkModuleList: [{}],
      checkModuleIdList: [],
    };
  }
  render(props) {
    let { checkModuleIdList } = this.state;
    return (
      <div className={style.modulelist}>
        <Row gutter={15}>
          {this.state.modulelist.map((val, i) => {
            return (
              <Col key={i} span={4}>
                <div
                  className={`${style.shoplist} ${
                    checkModuleIdList.includes(val.id) ? style.active : ""
                  }`}
                  onClick={this.checkModule.bind(this, val)}
                >
                  <Card
                    title={
                      <span>
                        <Iconfont type={val.icon} /> {val.title}
                      </span>
                    }
                  >
                    <p>{val.message}</p>
                  </Card>
                </div>
              </Col>
            );
          })}
        </Row>
        <Row className={style.shopbtn}>
          <Button type="primary" onClick={this.subModule}>
            提交
          </Button>
        </Row>
      </div>
    );
  }
  componentDidMount() {
    api.getNewAppConfigApi().then(({ data }) => {
      this.setState(
        {
          modulelist: data.data,
          checkModuleList: data.data.filter((val) => {
            return val.checked;
          }),
        },
        (_) => {
          console.log(this.state.checkModuleList);
          this.setState({
            checkModuleIdList: this.state.checkModuleList.map((val) => {
              return val.id;
            }),
          });
        }
      );
    });
  }
  checkModule = (mod) => {
    let checkModuleList = this.state.checkModuleList;
    let checkIndex = -1;
    let result = checkModuleList.some((item, index) => {
      if (item.id == mod.id) {
        checkIndex = index;
        return true;
      }
    });
    if (checkIndex !== -1) {
      checkModuleList.splice(checkIndex, 1);
    } else {
      checkModuleList.push(mod);
    }
    this.setState({
      checkModuleList,
      checkModuleIdList: checkModuleList.map((val) => {
        return val.id;
      }),
    });
    // api.setAppConfigApi({})
  };
  subModule = () => {
    api.getAppConfigApi(this.state.checkModuleList).then((res) => {
      console.log(res);
      message.success("修改成功");
      LibraryJs.localSet("apps", this.state.checkModuleList);
      setTimeout(() => {
        LibraryJs.routerGo("/moduleList");
      }, 1500);
    });
  };
}

export default ModuleList;
